package com.edu.dao.impl;

import com.edu.dao.BookDao;
import com.edu.entity.BookEntity;
import com.edu.entity.CategoryEntity;
import com.edu.utils.DatabaseManager;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

/**
 * com.edu.dao.impl
 * 2024/7/4 21:00
 *
 * @author Fancy
 * @version 1.0
 */
public class BookDaoImpl implements BookDao {
    private Connection connection;
    private CategoriesDaoImpl categoriesDao;

    public BookDaoImpl() {
        try {
            this.connection = DatabaseManager.getInstance().getConnection();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        categoriesDao = new CategoriesDaoImpl();
    }

    @Override
    public List<HashMap<String, Object>> getAllBook() {

        try {
            String sql = "SELECT * FROM Book";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            ResultSet resultSet = preparedStatement.executeQuery();
            List<HashMap<String, Object>> bookEntities = new LinkedList<>();

            while (resultSet.next()) {
                HashMap<String, Object> bookDataMap = new HashMap<>();

                bookDataMap.put("bookId", resultSet.getInt("book_id"));
                bookDataMap.put("title", resultSet.getString("title"));
                bookDataMap.put("author", resultSet.getString("author"));
                bookDataMap.put("publisher", resultSet.getString("publisher"));
                bookDataMap.put("price", resultSet.getDouble("price"));
                bookDataMap.put("stock", resultSet.getObject("stock", Integer.class)); // 处理可能为NULL的情况
                bookDataMap.put("description", resultSet.getString("description"));
                bookDataMap.put("coverImageUrl", resultSet.getString("cover_image_url"));
                CategoryEntity categor = categoriesDao.getCategoryById(resultSet.getInt("category_id"));
                bookDataMap.put("category", categor); // 尽管序列化时忽略，但仍存储
                bookEntities.add(bookDataMap);
            }
            return bookEntities;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Integer deleteBookInfo(String bookId) {
        try {
            String sql = "DELETE FROM Book WHERE book_id =?";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, bookId);
            return preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public HashMap<String, Object> getBookInfoById(String bookId) {
        try {
            String sql = "SELECT * FROM Book WHERE book_id = ?";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, bookId);
            ResultSet resultSet = preparedStatement.executeQuery();

            if (resultSet.next()) {
                HashMap<String, Object> bookDataMap = new HashMap<>();

                bookDataMap.put("bookId", resultSet.getInt("book_id"));
                bookDataMap.put("title", resultSet.getString("title"));
                bookDataMap.put("author", resultSet.getString("author"));
                bookDataMap.put("publisher", resultSet.getString("publisher"));
                bookDataMap.put("price", resultSet.getDouble("price"));
                bookDataMap.put("stock", resultSet.getObject("stock", Integer.class)); // 处理可能为NULL的情况
                bookDataMap.put("description", resultSet.getString("description"));
                bookDataMap.put("coverImageUrl", resultSet.getString("cover_image_url"));
                CategoryEntity categor = categoriesDao.getCategoryById(resultSet.getInt("category_id"));
                bookDataMap.put("category", categor); // 尽管序列化时忽略，但仍存储
                return bookDataMap;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null; // 如果没有找到用户，返回null
    }

    @Override
    public BookEntity getBookInfoById(int bookId) {
        try {
            String sql = "SELECT * FROM Book WHERE book_id = ?";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, bookId);
            ResultSet resultSet = preparedStatement.executeQuery();

            if (resultSet.next()) {
                BookEntity bookEntity = new BookEntity();

                bookEntity.setBookId(resultSet.getInt("book_id"));
                bookEntity.setTitle(resultSet.getString("title"));
                bookEntity.setAuthor(resultSet.getString("author"));
                bookEntity.setPublisher(resultSet.getString("publisher"));
                bookEntity.setPrice(resultSet.getDouble("price"));
                bookEntity.setStock(resultSet.getObject("stock", Integer.class)); // 处理可能为NULL的情况
                bookEntity.setDescription(resultSet.getString("description"));
                bookEntity.setCoverImageUrl(resultSet.getString("cover_image_url"));
                return bookEntity;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null; // 如果没有找到用户，返回null
    }
    @Override
    public Integer updateBookInfo(BookEntity book) {
        try {
            String sql = "UPDATE Book SET title = ?, author = ?, publisher = ?, price = ?, stock = ?, description =?  WHERE book_id = ?";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, book.getTitle());
            preparedStatement.setString(2, book.getAuthor());
            preparedStatement.setString(3, book.getPublisher());
            preparedStatement.setDouble(4, book.getPrice());
            preparedStatement.setDouble(5, book.getStock());
            preparedStatement.setString(6, book.getDescription());
            preparedStatement.setInt(7, book.getBookId());
            return preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public Integer addBookInfo(BookEntity book) {
        try {
            String sql = "INSERT INTO Book (title, author, publisher, price, stock, description, cover_image_url, category_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, book.getTitle());
            preparedStatement.setString(2, book.getAuthor());
            preparedStatement.setString(3, book.getPublisher());
            preparedStatement.setDouble(4, book.getPrice());
            preparedStatement.setDouble(5, book.getStock());
            preparedStatement.setString(6, book.getDescription());
            preparedStatement.setString(7, book.getCoverImageUrl());
            preparedStatement.setInt(8, book.getCategoryId());
            return preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public ArrayList<Integer> getBookIdInfoBySearch(String search) {
        try {
            String sql = "SELECT DISTINCT book_id FROM Book WHERE title LIKE ? " +
                    "OR author LIKE ? " +
                    "OR publisher LIKE ? " +
                    "OR description LIKE ?;";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, "%" + search + "%");
            preparedStatement.setString(2, "%" + search + "%");
            preparedStatement.setString(3, "%" + search + "%");
            preparedStatement.setString(4, "%" + search + "%");
            ResultSet rs = preparedStatement.executeQuery();
            ArrayList<Integer> bookIds = new ArrayList<>();
            while (rs.next()) {
                bookIds.add(rs.getInt("book_id"));
            }
            return bookIds;
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public double getPriceByBookId(int bookId) {
        try {
            String sql = "SELECT price FROM Book where book_id = ?";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, bookId);
            ResultSet rs = preparedStatement.executeQuery();
            if (rs.next()) {
                return rs.getInt("price");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
